<template>
  <div class="business-order">
    <x-header :left-options="{showBack: false}">
      <button-tab class="header-tab">
        <button-tab-item :selected="status==1" @on-item-click="statusChange">新运单</button-tab-item>
        <button-tab-item :selected="status===0" @on-item-click="statusChange">已完成</button-tab-item>
      </button-tab>
    </x-header>
    <div ref="scrollWrapper" class="scroll-wrapper">
      <box class="total pos-total">
        <div class="col">
          <x-button type="primary" mini @click.native="showDatetime">{{date}}</x-button>
        </div>
        <div class="col">
          <div>总运费：{{totalFare}}</div>
          <div>总单数：{{totalTotal}}</div>
        </div>
      </box>
      <div ref="cardWrapper" class="card-wrapper">
        <div class="month-list" v-for="(item, index) in list" :key="index" :data-index="index">
          <box class="total">
            <div class="col">
              <x-button type="primary" mini @click.native="showDatetime">{{YYYYMM(item.startTime)}}</x-button>
            </div>
            <div class="col">
              <div>总运费：{{amountSum(item.data)}}</div>
              <div>总单数：{{item.data.length}}</div>
            </div>
          </box>
          <div class="card" v-for="(item, index2) in item.data" :key="index2">
            <div v-if="status===1" class="card-main" @click="showOrderInfo(item)">
              <!-- <div class="prestate">等待通知</div> -->
              <flexbox :gutter="0">
                <flexbox-item :span="8">
                  <div class="row">
                    <span class="label">派单时间：</span>
                    <span class="value important">{{item.startTime}}</span>
                  </div>
                  <div class="row">
                    <span class="label">业务类型：</span>
                    <span class="value">{{item.import}}</span>
                  </div>
                  <div class="row">
                    <span class="label">门点地址：</span>
                    <span class="value">{{item.address}}</span>
                  </div>
                  <div class="row">
                    <span class="label">堆场：</span>
                    <span class="value">{{item.yard}}</span>
                  </div>
                  <div class="row">
                    <span class="label">备注：</span>
                    <span class="value">{{item.mome}}</span>
                  </div>
                </flexbox-item>
                <flexbox-item :span="4">
                  <div class="row">
                    <span class="label">箱型：</span>
                    <span class="value important">{{item.type}}</span>
                  </div>
                  <div class="row">
                    <span class="label">箱重：</span>
                    <span class="value">{{item.gweight}}</span>
                  </div>
                  <div class="row">
                    <span class="label">港区：</span>
                    <span class="value">{{item.port}}</span>
                  </div>
                  <div class="row">
                    <span class="label">提箱：</span>
                    <span class="value"></span>
                  </div>
                  <div class="row">
                    <span class="label">运费：</span>
                    <span class="value important">￥{{item.yunfei}}</span>
                  </div>
                </flexbox-item>
              </flexbox>
            </div>
            <div v-if="status===0" class="card-main" @click="showOrderInfo(item)">
              <!-- <div class="prestate">已完成</div> -->
              <flexbox :gutter="0">
                <flexbox-item :span="8">
                  <div class="row">
                    <span class="label">派单时间：</span>
                    <span class="value important">{{item.startTime}}</span>
                  </div>
                  <div class="row">
                    <span class="label">门点地址：</span>
                    <span class="value">{{item.address}}</span>
                  </div>
                </flexbox-item>
                <flexbox-item :span="4">
                  <div class="row">
                    <span class="label">箱型：</span>
                    <span class="value important">{{item.type}}</span>
                  </div>
                  <div class="row">
                    <span class="label">运费：</span>
                    <span class="value important">￥{{item.yunfei}}</span>
                  </div>
                </flexbox-item>
              </flexbox>
            </div>
            <div v-if="status===1" class="card-footer">
              <span class="value important">费用总计：￥{{item.vehiclesMoney }}</span>
              <div>
                <x-button @click.native="preRecorded(item)" type="primary" mini>预录</x-button>
                <x-button @click.native="applyFee(item)" type="primary" mini>申请费用</x-button>
              </div>
            </div>
            <div v-if="status===0" class="card-footer status0">
              <div @click="applyFee(item)">
                <span class="label">其他费用：</span>
                <span class="value">¥ {{item.vehiclesMoney}}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <load-more :show-loading="false" :tip="loadMoreText" background-color="#fbf9fe"></load-more>
    </div>
    <alert v-model="showPreReTip" title="提示">
      预录目前支持的港口有：<span class="important-alert-tip">外一、外二、外四、外五、洋一、洋三、洋四</span>，非以上港口暂不支持预录，非常抱歉。
    </alert>
  </div>
</template>

<script>
import {
  XHeader,
  ButtonTab,
  ButtonTabItem,
  XButton,
  Flexbox,
  FlexboxItem,
  Group,
  Radio,
  Box,
  LoadMore,
  Alert
} from 'vux'
import {
  getBusinessList
} from '../../api/api'
import util from '../../util/util'
import moment from 'moment'

export default {
  name: 'businessOrder',
  directives: {},
  components: {
    XHeader,
    ButtonTab,
    ButtonTabItem,
    XButton,
    Flexbox,
    FlexboxItem,
    Group,
    Radio,
    Box,
    LoadMore,
    Alert
  },
  data () {
    return {
      list: [],
      date: moment().format('YYYY-MM'),
      status: 1, // 新运单
      page: 1, // 第一页
      num: 15, // 每页加载多少条
      loadMoreText: '本月暂无记录',
      showPreReTip: false,
      curMonthIndex: 0,
      forwardLock: true,
      backLock: true,
      totalFare: 0,
      totalTotal: 0,
      loadLock: true,
    }
  },
  mounted () {
    const query = this.$router.currentRoute.query
    if (query.hasOwnProperty('status') && query.status === '完成') {
      this.status = 0
    }
    this.getList()
    
    let curMonthList = document.querySelectorAll('.month-list')[this.curMonthIndex]
    const scrollWrapper = this.$refs.scrollWrapper
    const cardWrapper = this.$refs.cardWrapper
    this.$refs.scrollWrapper.onscroll = (e) => {
      const st = scrollWrapper.scrollTop
      const coh = cardWrapper.offsetHeight
      const soh = scrollWrapper.offsetHeight
      if (curMonthList) {
        const ot = curMonthList.offsetTop
        const oh = curMonthList.offsetHeight
        // 下一月
        if (this.forwardLock && st > ot + oh) {
          this.forwardLock = false
          this.curMonthIndex++
          this.updateTotalPanel()
          curMonthList = document.querySelectorAll('.month-list')[this.curMonthIndex]
          if (curMonthList) {
            this.forwardLock = true
          }
        }
        // 上一月
        if (this.curMonthIndex > 0 && this.backLock && st <= ot) {
          this.backLock = false
          this.curMonthIndex--
          this.updateTotalPanel()
          curMonthList = document.querySelectorAll('.month-list')[this.curMonthIndex]
          if (curMonthList) {
            this.backLock = true
          }
        }
      } else {
        curMonthList = document.querySelectorAll('.month-list')[this.curMonthIndex]
      }

      if (cardWrapper) {
        if (this.loadLock && st >= coh - soh + 30) {
          this.loadLock = false
          this.page++
          this.getList()
        }
      } else {
        this.cardWrapper = this.$refs.cardWrapper
      }
    }
  },
  watch: {
    // 推送提示更新列表
    '$store.state.order.updBlUnix' (val) {
      this.getList()
    }
  },
  methods: {
    getList () {
      if (this.loadMoreText === '已加载全部') {
        return;
      }
      const user = util.getItem('$user')
      this.$vux.loading.show({
        text: '加载中'
      })
      this.initTotalPanel()
      getBusinessList({
        page: this.page,
        num: this.num,
        blno: '',
        userName: '',
        starTtime: '',
        endTime: `${this.date}-${moment(this.date).daysInMonth()}`,
        number: '',
        sendSomeoneId: user.uid,
        status: this.status
      }).then(res => {
        this.loadLock = true
        this.$vux.loading.hide()
        if (res.status === 200) {
          const data = res.data
          if (data.length === 0 && this.page === 1) {
            this.loadMoreText = '本月暂无数据'
            return
          }
          if (data.length < this.num) {
            this.loadMoreText = '已加载全部'
          }
          do {
            const minUnix = moment(moment(data[0].startTime).format('YYYY-MM') + '-01').unix()
            const fidx = data.findIndex(it => {
              return moment(it.startTime).unix() < minUnix
            })
            if (fidx > -1) {
              this.list.push({startTime: data[fidx - 1].startTime, data: data.splice(0, fidx)})
            } else {
              this.list.push({startTime: data[data.length - 1].startTime, data: data.splice(0, data.length)})
            }
          } while (data.length > 0)
          this.updateTotalPanel()
        } else {
          this.$vux.toast.text(res.msg)
        }
      })
    },
    updateTotalPanel() {
      this.date = moment(this.list[this.curMonthIndex].startTime).format('YYYY-MM')
      this.totalFare = this.amountSum(this.list[this.curMonthIndex].data)
      this.totalTotal = this.list[this.curMonthIndex].data.length
    },
    initTotalPanel() {
      this.totalFare = 0
      this.totalTotal = 0
    },
    showOrderInfo (item) {
      this.$store.state.orderDetail = item
      this.$router.push({
        path: '/main/order/bussinessOrderInfo',
        query: item
      })
    },
    applyFee (item) {
      this.$router.push({
        path: '/main/order/applyFee',
        query: item
      })
    },
    preRecorded (item) {
      if (!/W1|W2|W4|W5|Y1|Y3|Y4/.test(item.port)) {
        this.showPreReTip = true
        return
      }
      this.$router.push({
        path: '/main/order/preRecorded',
        query: item
      })
    },
    statusChange (index) {
      this.status = index === 0 ? 1 : index === 1 ? 0 : 1
      this.list = []
      this.page = 1
      this.loadMoreText = '本月暂无记录'
      this.date = moment().format('YYYY-MM')
      this.getList()
    },
    showDatetime() {
      this.$vux.datetime.show({
        cancelText: '取消',
        confirmText: '确定',
        format: 'YYYY-MM',
        value: this.date,
        onConfirm: (val) => {
          this.list = []
          this.curMonthIndex = 0
          this.forwardLock = true
          this.backLock = true
          this.loadLock = true
          this.page = 1
          this.loadMoreText = '本月暂无记录'
          this.date = val
          this.getList()
        }
      })
    },
    YYYYMM(date) {
      return moment(date).format('YYYY-MM')
    },
    amountSum(data) {
      let sum = 0;
      data.forEach(it => {
        sum += Number(it.yunfei) + it.vehiclesMoney
      })
      return sum
    }
  }
}
</script>

<style lang="less">
  .business-order{

    .important-alert-tip{
      text-decoration: underline;
      color: red;
    }
    .weui-btn + .weui-btn{
      margin: 0px 0px 0px 10px;
    }
    .weui-btn{
      margin-left: inherit;
      margin-right: inherit;
    }
    .pos-total{
      position: fixed;
      width: 100%;
      box-sizing: border-box;
      top: 45px;
      left: 0;
      z-index: 1;
    }
    .total{
      padding: 10px;
      display: flex;
      justify-content: space-between;
      color: #04BE02;
      background: #f3f3f3;
      align-items: center;
    }
    .scroll-wrapper{
      position: absolute;
      top: 46px;
      right: 0;
      bottom: 53px;
      left: 0;
      overflow-y: auto;
      padding-bottom: 10px;
      font-size: 12px;
      background: #f3f3f3;
    }
    .card-main{
      padding: 8px;
    }
    .card-footer{
      // border-top: 1px dashed #e6e6e6;
      padding: 3px 10px 10px 10px;
      display: flex;
      justify-content: space-between;
      .weui-btn_mini{
        line-height: 1.6;
        padding: 0 0.8em;
      }
      &.status0{
        padding: 5px 10px;
        margin-top: -5px;
        position: relative;
        z-index: 1;
        &>div{
          color: #04BE02 !important;
          text-decoration: underline;
          .label{
            color: #04BE02;
          }
        }
        
      }
    }
    .card{
      background: #ffffff;
      .card-main{
        overflow: hidden;
        position: relative;
        .prestate{
          text-align: center;
          width: 85px;
          padding: 2px 5px;
          border-radius: 3px;
          display: inline-block;
          background: #3a459a;
          color: #ffffff;
          font-size: 12px;
          position: absolute;
          top: 12px;
          left: -23px;
          transform: rotate(-45deg);
        }
      }
      .row{
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        width: 100%;
      }
      .label{
        color: #999999;
      }
      .value{
        &.important{
          color: red;
        }
      }
    }
    .card + .card{
      border-top: 1px solid #e6e6e6;
      // margin-top: 10px;
    }
  }
</style>
